package com.martin.lib_base.base

import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.martin.lib_base.common.CommonAdapter
import com.martin.lib_base.interfaces.ILoading
import com.martin.lib_base.model.LoadingModel
import kotlin.properties.Delegates

/**
 * @desc：基础视图持有者类
 */
abstract class BaseViewHolder<T, B : ViewDataBinding>(view: View) : RecyclerView.ViewHolder(view),
    ILoading {

    //数据视图绑定器
    var binding: B by Delegates.notNull()

    //加载框
    private val _loading by lazy {
        LoadingModel(itemView.context)
    }

    /**
     * 当创建ViewHolder时
     * 在这里创建 mBinding
     */
    open fun onCreateViewHolder() {
        binding = DataBindingUtil.bind(itemView)!!
    }

    /**
     * 绑定ViewHolder时
     * 一般在此将ViewModel设置到binding中
     * 并且处理点击事件
     */
    abstract fun onBindViewHolder(position: Int, item: Any?)

    /**
     * 获取实体类
     */
    protected fun getItemBean(item: Any?): T? {
        return try {
            item as T
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 获取RecyclerView
     */
    fun getRecyclerView(): RecyclerView? {
        var v: View = itemView
        var rv: RecyclerView? = null
        while (rv == null && v.parent != null) {
            val parent = v.parent as ViewGroup
            if (parent is RecyclerView) {
                rv = parent
            }
            v = parent
        }
        return rv
    }

    /**
     * 获取上下文对象
     */
    fun requireContext() = itemView.context

    /**
     * 通知条目点击事件
     */
    fun notifyItemClick(type: Int = 0) {
        getCommonAdapter()?.onItemClick(bindingAdapterPosition, type)
    }

    /**
     * 获取通用Adapter
     */
    protected fun getCommonAdapter(): CommonAdapter? {
        if (bindingAdapter is CommonAdapter) {
            return bindingAdapter as CommonAdapter
        }
        return null
    }

    /**
     * 展示加载弹窗
     */
    override fun showLoading() {
        _loading.showLoading()
    }

    /**
     * 隐藏加载弹窗
     */
    override fun dismissLoading() {
        _loading.dismissLoading()
    }

}